package security.lesson1;

public class Main {
    public static void main(String[] args) {
        System.out.println(pfCheng(34,60,51));
        System.out.println(pfCheng(345,89,101));
        System.out.println(pfCheng(10,10,10));
    }

    /**
     *
     * @param m 底数
     * @param a 指数
     * @param r 模数
     * @return
     */
    public static int pfCheng(int m,int a,int r){
        int[] b =new int[100];
        int length=0;
        int c=1;
        //将指数a转换为二进制
        do{
            b[length++]=a%2;
            a/=2;
        }while (a!=0);
        //记得减少一位，因为默认length++了
        length--;
        while (length>=0){
            c=(c*c)%r;
            if(b[length]==1){
                c=(c*m)%r;
            }
            length--;
        }
        return c;
    }
}
